<template>
  <div class="department">
    <div class="search-term">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
        <el-form-item label="部门名称">
          <el-input
                  v-model="searchInfo.dept_name"
                  placeholder="请输入部门名称"
                  clearable
                  @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchInfo.status" clearable placeholder="请选择部门状态">
            <el-option
                    v-for="dict in statusOptions"
                    :key="dict.item_value"
                    :label="dict.item_name"
                    :value="dict.item_value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
                  class="filter-item"
                  type="primary"
                  icon="el-icon-search"
                  @click="handleQuery"
          >搜索</el-button>
        </el-form-item>
      </el-form>
      <el-form>
        <el-form-item>
          <el-button
                  class="filter-item"
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="createDept()"
          >新增部门</el-button>
        </el-form-item>
      </el-form>
    </div>

      <el-table
                :data="tableData"
                row-key="ID"
                default-expand-all
                border
        >
          <el-table-column label="ID" width="50" prop="ID">
          <template slot-scope="scope">{{scope.row.ID}}</template>
        </el-table-column>
          <el-table-column prop="dept_code" label="部门编码" width="120" />
          <el-table-column prop="dept_name" label="部门名称" width="160"/>
          <el-table-column prop="company.company_name" label="公司名称" width="200" />
          <el-table-column prop="status" label="状态" width="60">
            <template slot-scope="scope">{{scope.row.status|formatString}}</template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="270"></el-table-column>
          <el-table-column label="创建时间" align="center" prop="createdAt" width="200">
            <template slot-scope="scope">
              <span>{{ scope.row.CreatedAt|formatDate}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                        @click="updateDept(scope.row)"
                        size="small"
                        type="primary"
                        icon="el-icon-edit"
                >编辑</el-button>
                <el-button @click="deleteDept(scope.row)" type="danger" icon="el-icon-delete" style="margin-left: 6px;" size="mini" >删除</el-button>
              </template>
            </el-table-column>
        </el-table>

      <el-pagination
              :current-page="page"
              :page-size="pageSize"
              :page-sizes="[10, 30, 50, 100]"
              :style="{float:'right',padding:'20px'}"
              :total="total"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
              layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
      <el-dialog :before-close="closeDialog" :title="dialogTitle" :visible.sync="dialogFormVisible" width="600px">
        <el-form :model="formData" :rules="rules" size="medium" label-width="110px" ref="elForm" >
         <el-form-item label="部门编码" prop="dept_code">
                <el-input  v-model="formData.dept_code" placeholder="请输入部门编码" :style="{width: '90%'}"></el-input>
              </el-form-item>
         <el-form-item label="部门名字" prop="dept_name">
            <el-input  v-model="formData.dept_name"  placeholder="请输入部门名称" :style="{width: '90%'}"></el-input>
         </el-form-item>
         <el-form-item label="公司" prop="company_code">
            <el-select  placeholder="请选择公司" v-model="formData.company_code" >
              <el-option
                      v-for="(item, i) in companyOptions"
                      :key="i"
                      :label="item.company_name"
                      :value="item.company_code"
              ></el-option>
            </el-select>
          </el-form-item>
         <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
                <el-radio
                        v-for="dict in statusOptions"
                        :key="dict.item_value"
                        :label="dict.item_value |formatBoolean"
                >{{ dict.item_name }}</el-radio>
              </el-radio-group>
         </el-form-item>
         <el-form-item label="备注" prop="remark">
                <el-input autocomplete="off" v-model="formData.remark" placeholder="请输入备注"  type="textarea" :style="{width: '90%'}"></el-input>
            </el-form-item>
        </el-form>
        <div class="dialog-footer" slot="footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button @click="enterDialog" type="primary">确 定</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
  import {
    getDepartmentList,
    createDepartment,
    deleteDepartment,
    updateDepartment
  } from "@/api/department";
  import { getCompany } from "@/api/company";
  import { formatTimeToStr } from '@/utils/date'
  import infoList from '@/mixins/infoList'
  export default {
    name: "department",
    mixins: [infoList],
    data() {
      return {
        listApi: getDepartmentList,
        dialogFormVisible: false,
        companyOptions: [],
        statusOptions:[],
        dialogTitle: '新增部门',
        type: '',   // 弹出dialog框类型 add/edit
        searchInfo: {
          dept_name: undefined,
          status: undefined
        },
        formData: {
          id: 0,   // 部门id primarykey
          dept_code: '',
          dept_name: '',
          status: true,
          remark: '',   // 描述信息
          company_code: ''
        },
        rules: {
          dept_code: [{ pattern: /^[0-9]*$/, message: "请输入部门编号 为数字", trigger: "blur" }],
          dept_name: [{ required: true, message: "请输入部门名字", trigger: "blur" }],
          remark: [
            { required: true, message: "请输入备注信息", trigger: "blur" }
          ],
        },


      }
    },
      methods: {
      handleQuery() {
        if (this.searchInfo.status==""){
          this.searchInfo.status=null
        }
        this.getTableData()
      },
      handleClose(done) {
        // this.initForm();
        done();
      },
      async updateDept(row) {
        this.type = "update";
        this.formData = row;
        this.dialogFormVisible = true;
        this.dialogTitle = '编辑公司';
        getCompany().then(response => {
              this.companyOptions = response.data.companyList;
          })
      },
     async createDept(){
         this.dialogTitle = '新增部门'
         this.type = 'create';
         this.initForm();
         this.dialogFormVisible = true;
         getCompany().then(response => {
             this.companyOptions = response.data.companyList;
         })
     },
      initForm() {
        this.formData = {
          dept_code: "",
          dept_name: "",
          company_code: "",
          status: true,
          remark: "",
        };
      },
      closeDialog() {
        // this.initForm();
        this.dialogFormVisible = false;
      },
      // 删除角色
      deleteDept(row) {
        this.$confirm("此操作将永久删除该部门, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
                .then(async () => {
                  this.visible = false;
                  const res = await deleteDepartment({ ID: row.ID });
                  if (res.code == 0) {
                    this.$message({
                      type: "success",
                      message: "删除成功!"
                    });
                    await  this.getTableData();
                  }
                })
                .catch(() => {
                  this.$message({
                    type: "info",
                    message: "已取消删除"
                  });
                });
      },
      async enterDialog() {
        this.$refs['elForm'].validate(async valid => {
          if (!valid) return
          let res;
          switch (this.type) {
            case "create":
              res = await createDepartment(this.formData);
              break;
            case "update":
              res = await updateDepartment(this.formData);
              break;
            default:
              res = await createDepartment(this.formData);
              break;
          }
          if (res.code == 0) {
            this.closeDialog();
            await this.getTableData();
          }
        })
      },
    },
    filters: {
      formatDate: function(time) {
      if (time != null && time != '') {
        var date = new Date(time)
        return formatTimeToStr(date, 'yyyy-MM-dd hh:mm:ss')
      } else {
        return ''
      }
    },
      formatString: function(bool) {
        if (bool != null) {
          return bool ? "正常" :"关闭";
        } else {
          return "";
        }
      },
      formatBoolean: function(s) {
        if (s == "1" ) {
          return true
        } else {
          return false;
        }
      }
  },
    async created() {
       await this.getTableData();
      this.statusOptions = this.getDicItemList('sys_common_status')

    }
  }
</script>

<style scoped lang="scss" >
    .department {
        .el-input-number {
            margin-left: 15px;
            span {
                display: none;
            }
        }
        .button-box {
            padding: 10px 20px;
            .el-button {
                float: right;
            }
        }
    }
    .link-type, .link-type:focus {
        color: #337ab7;
        cursor: pointer;
    }
  .warning {
    color: #dc143c;
  }

</style>
